package com.kuang.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Administrator
 * @date 2021/5/28 15:32
 * Description:可重入锁 lock版
 */
public class Demo02 {
    //Synchronized 默认是非公平锁 支持可重入锁
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            phone.sms();
        }, "A").start();

        new Thread(()->{
            phone.sms();
        }, "B").start();
    }
}

class Phone2 {
    Lock lock = new ReentrantLock();

    //Demo01中synchronized是一把锁，在这里使用lock，一共是两把锁
    public synchronized void sms() {
        lock.lock(); //细节问题: lock.lock(); lock.unlock();
        //lock锁必须配对，否则就会死在里面
        try {
            System.out.println(Thread.currentThread().getName()+" sms");
            call(); //这里也有锁
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public synchronized void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
